﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.Entities;
using BaHuan.Common;
using BaHuan.BusinessLayer;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuDoiHang : Form
    {
        #region Khai bao cuc bo && Load
        private PhieuDoiHangManagement phieudoihangMgt = new PhieuDoiHangManagement();
        private KhachHangManagement khachhangMgt = new KhachHangManagement();
        private ChiNhanhKhachHangManagement chinhanhkhachangMgt = new ChiNhanhKhachHangManagement();
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private HangHoaManagement hanghoaMgt = new HangHoaManagement();
        private KhayDungManagement khaydungMgt = new KhayDungManagement();
        private CTPhieuXuatHangManagement ctphieuxuathangMgt = new CTPhieuXuatHangManagement();
        private CTPhieuDoiHangManagement ctphieudoihangMgt = new CTPhieuDoiHangManagement();
        private KhoManagement khoMgt = new KhoManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private DonViTinhMgt donvitinhMgt = new DonViTinhMgt();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private int idLoaiPhieu = 4;
        private bool IsEdit = false;
        private PhieuDoiHang phieudoihang;
        private List<CTPhieuDoiHang> lstmCTPhieuDoiHang;
        private List<CTPhieuDoiHang> lstDeleteCTPhieuDoiHang = new List<CTPhieuDoiHang>();        

        public PhieuDoiHang PhieuDoiHang
        {
            get { return this.phieudoihang; }
            set { this.phieudoihang = value; }
        }

        private NhanVien nhanvien;
        public NhanVien NhanVien
        {
            get { return this.nhanvien; }
            set { this.nhanvien = value; }
        }

        public FrmPhieuDoiHang(PhieuDoiHang phieudoihang)
        {
            InitializeComponent();
            BindingToCbo();
            btnSua.Enabled = true;
            btnXoa.Enabled = true;
            btnDinhKhoan.Enabled = true;
            btnLuu.Enabled = false;

            gpbThongTin.Enabled = false;
            gpbTien.Enabled = false;
            this.PhieuDoiHang = phieudoihang;

            ResultObj result = new ResultObj();

            result = chinhanhctyMgt.GetAllChiNhanhCongTy();
            ChiNhanhCongTy chinhanhcongty = (from cn in (List<ChiNhanhCongTy>)result.Result
                                             where cn.Id == this.phieudoihang.IdChiNhanhCongTy && cn.IsDelete == 0
                                             select cn).FirstOrDefault();

            dtOld = this.phieudoihang.NgayThang;
            dtpNgay.Value = this.phieudoihang.NgayThang;

            prefixOld = this.phieudoihang.Prefix;
            cboPrefix.Text = this.phieudoihang.Prefix;
            txtMaSo.Text = this.phieudoihang.OrderNumber;
            
            txtSoChungTu.Text = this.phieudoihang.SoChungTu;
            txtNguoiLap.Text = this.phieudoihang.NguoiLapPhieu;
            txtDiaChi.Text = this.phieudoihang.DiaChi;
            txtLyDo.Text = this.phieudoihang.LyDo;
            txtTongTienHang.Text = this.phieudoihang.TongTienHang.ToString();
            txtTienChietKhau.Text = this.phieudoihang.TienChietKhau.ToString();
            txtTienVAT.Text = this.phieudoihang.TienThue.ToString();
            txtTongCong.Text = this.phieudoihang.TongCong.ToString();
            lblId.Text = this.phieudoihang.Id.ToString();

            cboKho.Text = chinhanhcongty.TenChiNhanh;
            cboKhachHang.SelectedIndex = cboKhachHang.FindString(this.phieudoihang.KhachHang);
            cboChiNhanhKhachHang.SelectedIndex = cboChiNhanhKhachHang.FindString(this.phieudoihang.ChiNhanhKhachHang);
            

            result = ctphieudoihangMgt.GetAllCTPhieuDoiHang();
            List<CTPhieuDoiHang> lstCTPhieuDoiHang = (from ct in (List<CTPhieuDoiHang>)result.Result
                                                      where ct.IdPhieuDoiHang == phieudoihang.Id &&
                                                      ct.IsDelete == 0
                                                      select ct).ToList();
            
            for (int i = 0; i < lstCTPhieuDoiHang.Count; i++)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
                List<HangHoa> lstHangThanhPham = GetAllHangHoa();
                cboCell.DataSource = lstHangThanhPham;
                cboCell.DisplayMember = "Ten";
                cboCell.ValueMember = "MaSo";
                cboCell.Value = lstCTPhieuDoiHang[i].MaHang;
                row.Cells.Add(cboCell);

                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].MaHang;
                row.Cells.Add(cell);

                cboCell = new DataGridViewComboBoxCell();
                cboCell.DataSource = GetAllDonViTinh();
                cboCell.DisplayMember = "TenDVT";
                cboCell.ValueMember = "TenDVT";
                cboCell.Value = lstCTPhieuDoiHang[i].DonViTinh;
                row.Cells.Add(cboCell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].SoLuong;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].DonGia;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].ThanhTien;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].SoKg;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].DonViTinhQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].SoLuongQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuDoiHang[i].Id;
                row.Cells.Add(cell);

                dgvChiTiet.Rows.Add(row);
            }

            dgvChiTiet.Enabled = false;
        }

        public FrmPhieuDoiHang(PhieuXuatHang phieuxuathang, NhanVien nhanvien)
        {
            InitializeComponent();

            BindingToCbo();
            FillDataPhieuXuatHangToControls(phieuxuathang);
            txtNguoiLap.Text = nhanvien.HoTen;
        }
        #endregion

        #region Xu ly Button
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo!", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                ResultObj result = new ResultObj();

                result = ctphieudoihangMgt.GetAllCTPhieuDoiHang();
                List<CTPhieuDoiHang> lstctphieudoihang = (from ct in (List<CTPhieuDoiHang>)result.Result
                                                          where ct.IdPhieuDoiHang == phieudoihang.Id &&
                                                          ct.IsDelete == 0
                                                          select ct).ToList();

                phieudoihang.Id = Convert.ToInt32(lblId.Text);
                phieudoihang.IsDelete = 1;
                result = phieudoihangMgt.UpdatePhieuDoiHang(phieudoihang);

                for (int i = 0; i < lstctphieudoihang.Count; i++)
                {
                    lstctphieudoihang[i].IsDelete = 1;
                    result = ctphieudoihangMgt.UpdateCTPhieuDoiHang(lstctphieudoihang[i]);
                }

                EditOrRemoveDinhKhoan(phieudoihang.MaSo);

                List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                where (q.SoChungTuXuat == phieudoihang.MaSo || q.SoChungTuXuat == phieudoihang.MaSo)
                                                select q).ToList();

                if (lstQuanLykho.Count > 0)
                {
                    foreach (QuanLyKho q in lstQuanLykho)
                    {
                        q.IsDelete = 1;
                        result = quanlykhoMgt.UpdateQuanLyKho(q);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == q.IdHangHoa && h.NoiLuuTru == ((ChiNhanhCongTy)cboKho.SelectedItem).TenChiNhanh
                                           select h).FirstOrDefault();

                        int index = lstctphieudoihang.FindIndex(p => p.MaHang == hanghoa.MaSo);
                        hanghoa.SoLuong -= lstctphieudoihang[index].SoLuong;
                        result = hanghoaMgt.UpdateHangHoa(hanghoa);
                    }
                }

                if (result.ReturnCode > 0)
                {
                    MessageBox.Show("Đã xóa thành công.", "Thông báo!");
                    this.Close();
                }
                else if (result.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng !", "Thông báo");
                else
                    MessageBox.Show("Thất bại !");
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {            
            gpbTien.Enabled = true;
            dgvChiTiet.Enabled = true;
            dgvChiTiet.ReadOnly = false;
            gpbThongTin.Enabled = true;
            dtpNgay.Select();
            IsEdit = true;

            btnLuu.Enabled = true;
            btnDinhKhoan.Enabled = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;           
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            FrmDinhKhoanPhieuDoiHang frmDinhKhoanPhieuDoiHang = new FrmDinhKhoanPhieuDoiHang();
            frmDinhKhoanPhieuDoiHang.PhieuDoiHang = this.phieudoihang;
            frmDinhKhoanPhieuDoiHang.Show();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (txtMaSo.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mã phiếu");
                return;
            }

            if (txtLyDo.Text.ToLower() != "xuất đổi hàng" && txtLyDo.Text.ToLower() != "nhập đổi hàng")
            {
                MessageBox.Show("Vui lòng nhập lý do là \"Xuất đổi hàng\" hoặc \"Nhập đổi hàng\" !","Thông báo");
                txtLyDo.Select();
                return;
            }
            
            ResultObj resultObj = new ResultObj();

            phieudoihang = new PhieuDoiHang();
            phieudoihang.Prefix = cboPrefix.Text;
            phieudoihang.OrderNumber = txtMaSo.Text;
            phieudoihang.MaSo = cboPrefix.Text + "/" + dtpNgay.Value.ToString("MM") + dtpNgay.Value.ToString("yy") + "/" + txtMaSo.Text;
            phieudoihang.History = "";
            phieudoihang.NgayThang = dtpNgay.Value;
            phieudoihang.NguoiLapPhieu = txtNguoiLap.Text;
            phieudoihang.SoChungTu = txtSoChungTu.Text;
            phieudoihang.KhachHang = ((KhachHang)cboKhachHang.SelectedItem).Ten;
            phieudoihang.ChiNhanhKhachHang = cboChiNhanhKhachHang.SelectedValue != null ? ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Ten : "";
            phieudoihang.DiaChi = txtDiaChi.Text;
            phieudoihang.LyDo = txtLyDo.Text;
            phieudoihang.IdChiNhanhCongTy = Convert.ToInt32(cboKho.SelectedValue.ToString());
            phieudoihang.TongTienHang = Convert.ToInt64(txtTongTienHang.Text);
            phieudoihang.ChietKhau = Convert.ToInt64(txtTienChietKhau.Text);
            phieudoihang.Thue = Convert.ToInt64(txtTienVAT.Text);
            phieudoihang.TongCong = Convert.ToInt64(txtTongCong.Text);          

            if (!IsEdit)
            {
                phieudoihang.IsDelete = 0;
                resultObj = phieudoihangMgt.SaveNewPhieuDoiHang(phieudoihang);
                phieudoihang.Id = resultObj.ReturnCode;
                lblId.Text = resultObj.ReturnCode.ToString();

                for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                {
                    CTPhieuDoiHang ctphieudoihang = new CTPhieuDoiHang();

                    ctphieudoihang.IdPhieuDoiHang = phieudoihang.Id;
                    ctphieudoihang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                    ctphieudoihang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                    ctphieudoihang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                    ctphieudoihang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                    ctphieudoihang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                    ctphieudoihang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                    ctphieudoihang.SoKg = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value);
                    ctphieudoihang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                    ctphieudoihang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                    ctphieudoihang.IsDelete = 0;

                    resultObj = ctphieudoihangMgt.SaveNewCTPhieuDoiHang(ctphieudoihang);
                    dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode;
                }
            }
            else
            {
                phieudoihang.Id = Convert.ToInt32(lblId.Text);
                resultObj = phieudoihangMgt.UpdatePhieuDoiHang(phieudoihang);

                if (this.lstmCTPhieuDoiHang != null)
                    lstmCTPhieuDoiHang.Clear();

                lstmCTPhieuDoiHang = (from ctpdh in GetAllCTPhieuDoiHang()
                                      where ctpdh.IdPhieuDoiHang == this.phieudoihang.Id
                                      select ctpdh).ToList();

                //Tim ra so dong update that su sau khi da xoa hoac chua xoa
                int countUpdate = this.lstmCTPhieuDoiHang.Count - this.lstDeleteCTPhieuDoiHang.Count;
                int countInsert = 0;

                //Tim so dong moi' ma` nguoi` dung` vua` them vao`
                if ((dgvChiTiet.Rows.Count - countUpdate) > 1)
                    countInsert = dgvChiTiet.Rows.Count - countUpdate;

                if (countUpdate > 0)
                {
                    for (int i = 0; i < countUpdate; i++)
                    {
                        CTPhieuDoiHang ctphieudoihang = new CTPhieuDoiHang();

                        ctphieudoihang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctphieudoihang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctphieudoihang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctphieudoihang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                        ctphieudoihang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                        ctphieudoihang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                        ctphieudoihang.SoKg = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value);
                        ctphieudoihang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                        ctphieudoihang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                        ctphieudoihang.Id = Convert.ToInt32(dgvChiTiet.Rows[i].Cells[9].Value);
                        ctphieudoihang.IdPhieuDoiHang = phieudoihang.Id;
                        ctphieudoihang.IsDelete = 0;

                        resultObj = ctphieudoihangMgt.UpdateCTPhieuDoiHang(ctphieudoihang);
                    }
                }

                if (countInsert > 1)
                {
                    for (int i = countUpdate; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        CTPhieuDoiHang ctphieudoihang = new CTPhieuDoiHang();

                        ctphieudoihang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctphieudoihang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctphieudoihang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctphieudoihang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                        ctphieudoihang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value);
                        ctphieudoihang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                        ctphieudoihang.SoKg = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value);
                        ctphieudoihang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                        ctphieudoihang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                        ctphieudoihang.IdPhieuDoiHang = phieudoihang.Id;
                        ctphieudoihang.IsDelete = 0;

                        resultObj = ctphieudoihangMgt.SaveNewCTPhieuDoiHang(ctphieudoihang);
                        dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode.ToString();
                    }
                }
            }

            if (resultObj.ReturnCode > 0)
            {
                MessageBox.Show("Lưu thành công", "Thông báo");
                //sau khi insert thanh cong
                if (!IsEdit)
                {
                    btnSua.Enabled = true;
                    if (txtLyDo.Text.ToLower() == "xuất đổi hàng")
                    {
                        ////***insert quan ly kho va hang hoa cho Phieu Doi Hang
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where (q.SoChungTuXuat == phieudoihang.MaSo)
                                                        select q).ToList();

                        if (lstQuanLykho.Count <= 0)
                        {
                            ResultObj resObj = new ResultObj();

                            List<Kho> lstKho = (from k in GetAllKho()
                                                where k.TenKho == "155"
                                                select k).ToList();

                            for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                            {
                                string maso = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                                List<HangHoa> lstHangHoa = (from h in GetAllHangHoa()
                                                            where h.MaSo == maso
                                                            select h).ToList();

                                //update bang hang hoa
                                if (lstHangHoa.Count > 0)
                                {
                                    lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                    if (lstHangHoa[0].SoLuong < 0)
                                    {
                                        lstHangHoa[0].SoLuong = 0;
                                    }

                                    resObj = hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                }
                                //insert bang Quan ly kho
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    QuanLyKho quanlykho = new QuanLyKho();
                                    quanlykho.IdKho = lstKho[0].Id;
                                    quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                    quanlykho.SoChungTuNhap = "";
                                    quanlykho.SoChungTuXuat = phieudoihang.MaSo;

                                    resObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                }
                            }
                        }
                    }
                    else if (txtLyDo.Text.ToLower() == "nhập đổi hàng")
                    {
                        ////***insert quan ly kho va hang hoa cho Phieu Doi Hang
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where (q.SoChungTuNhap == phieudoihang.MaSo)
                                                        select q).ToList();
                        if (lstQuanLykho.Count <= 0)
                        {
                            ResultObj resObj = new ResultObj();

                            List<Kho> lstKho = (from k in GetAllKho()
                                                where k.TenKho == "155"
                                                select k).ToList();

                            for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                            {
                                string maso = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                                List<HangHoa> lstHangHoa = (from h in GetAllHangHoa()
                                                            where h.MaSo == maso
                                                            select h).ToList();

                                //update bang hang hoa
                                if (lstHangHoa.Count > 0)
                                {
                                    lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                    resObj = hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                }

                                //insert bang Quan ly kho
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    QuanLyKho quanlykho = new QuanLyKho();
                                    quanlykho.IdKho = lstKho[0].Id;
                                    quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                    quanlykho.SoChungTuNhap = phieudoihang.MaSo;
                                    quanlykho.SoChungTuXuat = "";

                                    resObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                }
                            }
                        }
                    }
                }//end insert
                //sau khi update phieu thanh cong
                else
                {
                    List<ChiNhanhCongTy> lstChiNhanhCTy = (from cn in GetAllChiNhanhCongTy()
                                                           where cn.Id == this.phieudoihang.IdChiNhanhCongTy
                                                           select cn).ToList();

                    List<Kho> lstKho = (from k in GetAllKho()
                                        where k.TenKho == "155"
                                        select k).ToList();
                    //bat dau truong hop "xuat doi hang"
                    if (txtLyDo.Text.ToLower() == "xuất đổi hàng")
                    {
                        //****** update quan ly kho va hang hoa ******//
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where (q.SoChungTuXuat == this.phieudoihang.MaSo || q.SoChungTuNhap == this.phieudoihang.MaSo)
                                                        select q).ToList();

                        if (lstQuanLykho.Count > 0)
                        {
                            

                            //reset lai soluong cua bang hang hoa truoc khi cap nhat soluong hang hoa moi
                            for (int i = 0; i < this.lstmCTPhieuDoiHang.Count; i++)
                            {
                                CTPhieuDoiHang ctdhTemp = (from ct in this.lstDeleteCTPhieuDoiHang
                                                            where ct.Id == this.lstmCTPhieuDoiHang[i].Id
                                                            select ct).FirstOrDefault();
                                if (ctdhTemp == null)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == this.lstmCTPhieuDoiHang[i].MaHang) && (htp.Ten == this.lstmCTPhieuDoiHang[i].TenHang) &&
                                                                        (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();
                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + this.lstmCTPhieuDoiHang[i].SoLuong;
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                             where qlk.IdHangHoa == lstHangHoa[0].Id && (qlk.SoChungTuXuat == this.phieudoihang.MaSo || qlk.SoChungTuNhap == this.phieudoihang.MaSo)
                                                                             select qlk).ToList();

                                        if (lstQuanLyKhoReset.Count > 0)
                                        {
                                            lstQuanLyKhoReset[0].IsDelete = 1;
                                            quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                        }
                                    }
                                }
                            }

                            //bat dau cap nhat lai soluong moi vao bang Hang Hoa va quan ly kho
                            int countUpdate = this.lstmCTPhieuDoiHang.Count - this.lstDeleteCTPhieuDoiHang.Count;
                            int countInsert = 0;

                            if ((dgvChiTiet.Rows.Count - countUpdate) > 1)
                                countInsert = dgvChiTiet.Rows.Count - countUpdate;

                            if (countUpdate > 0)
                            {
                                for (int i = 0; i < countUpdate; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }

                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //update bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = "";
                                        quanlykho.SoChungTuXuat = this.phieudoihang.MaSo;

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }

                                }
                            }

                            if (countInsert > 1)
                            {
                                for (int i = countUpdate; i < dgvChiTiet.Rows.Count - 1; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }

                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //insert bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = "";
                                        quanlykho.SoChungTuXuat = this.phieudoihang.MaSo;

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }
                                }
                            }
                        }
                        //delete cac CTPhieuDoiHang do nguoi dung chuot phai "XOA"
                        if (this.lstDeleteCTPhieuDoiHang.Count > 0)
                        {

                            foreach (CTPhieuDoiHang ctdh in this.lstDeleteCTPhieuDoiHang)
                            {
                                List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                            where (htp.MaSo == ctdh.MaHang) && (htp.Ten == ctdh.TenHang) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                            select htp).ToList();

                                //xoa CTPhieuDoiHang
                                ctdh.IsDelete = 1;
                                ctphieudoihangMgt.UpdateCTPhieuDoiHang(ctdh);

                                //xoa bang hang hoa
                                if (lstHangHoa.Count > 0)
                                {
                                    lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + ctdh.SoLuong;
                                    if (lstHangHoa[0].SoLuong < 0)
                                    {
                                        lstHangHoa[0].SoLuong = 0;
                                    }

                                    hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                }

                                //xoa quan ly kho
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                         where qlk.IdHangHoa == lstHangHoa[0].Id && (qlk.SoChungTuXuat == this.phieudoihang.MaSo || qlk.SoChungTuNhap == this.phieudoihang.MaSo)
                                                                         select qlk).ToList();

                                    if (lstQuanLyKhoReset.Count > 0)
                                    {
                                        lstQuanLyKhoReset[0].IsDelete = 1;
                                        quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                    }
                                }
                            }
                        }
                    }//ket thuc truong hop "xuat doi hang"
                    //bat dau truong hop "nhap "
                    else if (txtLyDo.Text.ToLower() == "nhập đổi hàng")
                    {
                        //****** update quan ly kho va hang hoa ******//
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where (q.SoChungTuXuat == this.phieudoihang.MaSo || q.SoChungTuNhap == this.phieudoihang.MaSo)
                                                        select q).ToList();

                        if (lstQuanLykho.Count > 0)
                        {

                            //reset lai soluong cua bang hang hoa truoc khi cap nhat soluong hang hoa moi
                            for (int i = 0; i < this.lstmCTPhieuDoiHang.Count; i++)
                            {
                                CTPhieuDoiHang ctdhTemp = (from ct in this.lstDeleteCTPhieuDoiHang
                                                            where ct.Id == this.lstmCTPhieuDoiHang[i].Id
                                                            select ct).FirstOrDefault();

                                if (ctdhTemp == null)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == this.lstmCTPhieuDoiHang[i].MaHang) && (htp.Ten == this.lstmCTPhieuDoiHang[i].TenHang) &&
                                                                        (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();
                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - this.lstmCTPhieuDoiHang[i].SoLuong;
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                             where qlk.IdHangHoa == lstHangHoa[0].Id && (qlk.SoChungTuXuat == this.phieudoihang.MaSo || qlk.SoChungTuNhap == this.phieudoihang.MaSo)
                                                                             select qlk).ToList();

                                        if (lstQuanLyKhoReset.Count > 0)
                                        {
                                            lstQuanLyKhoReset[0].IsDelete = 1;
                                            quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                        }
                                    }
                                }
                            }

                            //bat dau cap nhat lai soluong moi vao bang Hang Hoa va quan ly kho
                            int countUpdate = this.lstmCTPhieuDoiHang.Count - this.lstDeleteCTPhieuDoiHang.Count;
                            int countInsert = 0;

                            if ((dgvChiTiet.Rows.Count - countUpdate) > 1)
                                countInsert = dgvChiTiet.Rows.Count - countUpdate;

                            if (countUpdate > 0)
                            {
                                for (int i = 0; i < countUpdate; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //update bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = this.phieudoihang.MaSo;
                                        quanlykho.SoChungTuXuat = "";

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }

                                }
                            }

                            if (countInsert > 1)
                            {
                                for (int i = countUpdate; i < dgvChiTiet.Rows.Count - 1; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //insert bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = this.phieudoihang.MaSo;
                                        quanlykho.SoChungTuXuat = "";

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }
                                }
                            }
                        }
                        //delete cac CTPhieuDoiHang do nguoi dung chuot phai "XOA"
                        if (this.lstDeleteCTPhieuDoiHang.Count > 0)
                        {

                            foreach (CTPhieuDoiHang ctdh in this.lstDeleteCTPhieuDoiHang)
                            {
                                List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                            where (htp.MaSo == ctdh.MaHang) && (htp.Ten == ctdh.TenHang) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                            select htp).ToList();

                                //xoa CTPhieuDoiHang
                                ctdh.IsDelete = 1;
                                ctphieudoihangMgt.UpdateCTPhieuDoiHang(ctdh);

                                //xoa bang hang hoa
                                if (lstHangHoa.Count > 0)
                                {
                                    lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - ctdh.SoLuong;
                                    if (lstHangHoa[0].SoLuong < 0)
                                    {
                                        lstHangHoa[0].SoLuong = 0;
                                    }
                                    hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                }

                                //xoa quan ly kho
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                         where qlk.IdHangHoa == lstHangHoa[0].Id && (qlk.SoChungTuXuat == this.phieudoihang.MaSo || qlk.SoChungTuNhap == this.phieudoihang.MaSo)
                                                                         select qlk).ToList();

                                    if (lstQuanLyKhoReset.Count > 0)
                                    {
                                        lstQuanLyKhoReset[0].IsDelete = 1;
                                        quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                    }
                                }
                            }
                        }
                    }//end update

                    if (this.lstDeleteCTPhieuDoiHang.Count > 0)
                        this.lstDeleteCTPhieuDoiHang.Clear();

                    btnLuu.Enabled = false;
                    btnDinhKhoan.Enabled = true;
                    btnSua.Enabled = true;
                    btnXoa.Enabled = true;

                    dgvChiTiet.ReadOnly = true;
                    gpbThongTin.Enabled = false;
                }
            }
            else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
            else
                MessageBox.Show("Thất bại");
        }
        #endregion

        #region Xu ly su kien
        private void cboKhachHang_SelectedValueChanged(object sender, EventArgs e)
        {
            KhachHang khachhang = (from c in GetAllKhachHang()
                                   where c.Id == ((KhachHang)cboKhachHang.SelectedItem).Id
                                   select c).FirstOrDefault();
            if (khachhang != null)
            {
                txtDiaChi.Text = khachhang.DiaChi;
                lblChietKhau.Text = khachhang.ChietKhau.ToString();
            }
        }

        private void cboChiNhanhKhachHang_SelectedValueChanged(object sender, EventArgs e)
        {
            ChiNhanhKhachHang chinhanhkhachhang = (from c in GetAllChiNhanhKhachHang()
                                                   where c.Id == ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Id
                                                   select c).FirstOrDefault();
            if (chinhanhkhachhang != null)
            {
                txtDiaChi.Text = chinhanhkhachhang.DiaChi;
                lblChietKhau.Text = chinhanhkhachhang.ChietKhau.ToString();
            }
        }

        private void dgvChiTiet_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgay.Value);
        }

        private void dtpNgay_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgay.Value)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgay.Value);
        }

        public void BindingToCbo()
        {
            cboKho.DataSource = GetAllChiNhanhCongTy();
            cboKho.DisplayMember = "TenChiNhanh";
            cboKho.ValueMember = "Id";

            cboKhachHang.DataSource = GetAllKhachHang();
            cboKhachHang.DisplayMember = "Ten";
            cboKhachHang.ValueMember = "Id";

            cboChiNhanhKhachHang.DataSource = GetAllChiNhanhKhachHang();
            cboChiNhanhKhachHang.DisplayMember = "Ten";
            cboChiNhanhKhachHang.ValueMember = "Id";

            cboTenHang.DataSource = GetAllHangHoa();
            cboTenHang.DisplayMember = "Ten";
            cboTenHang.ValueMember = "Id";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        private void dgvChiTiet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                    {
                        MessageBox.Show("Vui lòng chọn đơn vị tính !", "Thông báo");
                        return;
                    }
                }

                if (e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
                {
                    long num;
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                    {
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                            dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                        if (!Int64.TryParse(dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                        {
                            MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                            dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                            return;
                        }
                    }
                }

                if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
                {
                    long soluong = 0;
                    long dongia = 0;

                    if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value != null)
                    {
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString() != "")
                        {
                            soluong = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString());
                            if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (soluong * 300).ToString();
                            else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                            {
                                List<HangHoa> lstHangThanhPham = (from htp in GetAllHangHoa()
                                                                  where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                                                  select htp).ToList();
                                if (lstHangThanhPham.Count > 0)
                                {
                                    List<KhayDung> lstKhayDung = (from kd in GetAllKhayDung()
                                                                  where kd.Id == lstHangThanhPham[0].IdKhayDung
                                                                  select kd).ToList();
                                    if (lstKhayDung.Count > 0)
                                    {
                                        dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (lstKhayDung[0].SoLuongHop * soluong).ToString();
                                    }
                                }
                            }
                            else
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString();
                        }
                        else
                        {
                            soluong = 0;
                            dgvChiTiet.Rows[e.RowIndex].Cells[3].Value = "0";
                        }
                    }

                    dongia = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[4].Value.ToString());
                    long thanhtien = soluong * dongia;
                    dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = thanhtien.ToString();

                    long tongthanhtienBaoBi = 0;
                    long tongthanhpham = 0;
                    long chietkhau = 0;
                    long vat = 0;
                    long tongcong = 0;

                    for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        string sCompare = dgvChiTiet.Rows[i].Cells[1].Value.ToString().Substring(0, 1).ToLower();
                        if (sCompare == "8" || sCompare == "9" || sCompare == "b")
                        {
                            tongthanhtienBaoBi += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        }
                        else
                        {
                            tongthanhpham += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        }
                    }

                    txtTongTienHang.Text = tongthanhpham.ToString();
                    txtTienBaoBi.Text = tongthanhtienBaoBi.ToString();
                    chietkhau = tongthanhpham * Convert.ToInt64(lblChietKhau.Text) / 100;
                    txtTienChietKhau.Text = chietkhau.ToString();
                    vat = (tongthanhpham * Convert.ToInt64(lblThue.Text) - Convert.ToInt64(txtTienChietKhau.Text)) / 100;
                    txtTienVAT.Text = vat.ToString();
                    tongcong = (tongthanhpham + vat + tongthanhtienBaoBi) - chietkhau;
                    txtTongCong.Text = tongcong.ToString();
                }

                if (e.ColumnIndex == 2)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Hộp";
                    else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Quả";
                    else
                        dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString();
                }

                if (e.ColumnIndex == 0)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[0].Value != null)
                    {
                        HangHoa hanghoa = (from htp in GetAllHangHoa()
                                           where htp.Id == Convert.ToInt32(dgvChiTiet.Rows[e.RowIndex].Cells[0].Value)
                                           select htp).FirstOrDefault();

                        if (hanghoa != null)
                        {
                            if (hanghoa.Id != -1)
                            {
                                dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = hanghoa.MaSo;
                                dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                            }
                        }
                    }
                }

                if (e.ColumnIndex == 1)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[1].Value != null)
                    {
                        HangHoa hanghoa = (from htp in GetAllHangHoa()
                                           where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                           select htp).FirstOrDefault();
                        if (hanghoa != null)
                        {
                            if (hanghoa.Id != -1)
                            {
                                dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                                dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = hanghoa.MaSo;
                            }
                        }
                    }
                }
            }
        }

        private void dgvChiTiet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        public void FillDataPhieuXuatHangToControls(PhieuXuatHang phieuxuathang)
        {
            dgvChiTiet.AllowUserToAddRows = true;
            dgvChiTiet.AutoGenerateColumns = false;

            txtSoChungTu.Text = phieuxuathang.MaSo;
            cboKhachHang.Text = phieuxuathang.KhachHang;
            cboChiNhanhKhachHang.Text = phieuxuathang.ChiNhanhKhachHang;

            cboKho.SelectedValue = phieuxuathang.IdChiNhanhCongTy;
            txtTongTienHang.Text = phieuxuathang.TongTienHang.ToString();
            txtTienChietKhau.Text = phieuxuathang.TienChietKhau.ToString();
            txtTienVAT.Text = phieuxuathang.TienVAT.ToString();
            txtTongCong.Text = phieuxuathang.TongCong.ToString();

            lblChietKhau.Text = phieuxuathang.ChietKhau.ToString();
            lblThue.Text = phieuxuathang.VAT.ToString();

            List<CTPhieuXuatHang> lstCTPhieuXuatHang = (from ct in GetAllCTPhieuXuatHang()
                                         where ct.IdPhieuXuatHang == phieuxuathang.Id
                                         select ct).ToList();

            
            for (int i = 0; i < lstCTPhieuXuatHang.Count; i++)
            {
                DataGridViewRow row = new DataGridViewRow();

                DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
                List<HangHoa> lstHangThanhPham = GetAllHangHoa();
                cboCell.DataSource = lstHangThanhPham;
                cboCell.DisplayMember = "Ten";
                cboCell.ValueMember = "MaSo";
                cboCell.Value = lstCTPhieuXuatHang[i].MaHang;
                row.Cells.Add(cboCell);

                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].MaHang;
                row.Cells.Add(cell);

                cboCell = new DataGridViewComboBoxCell();
                cboCell.Items.Add("Khay");
                cboCell.Items.Add("Cây");
                cboCell.Items.Add("Hộp");
                cboCell.Items.Add("Vỉ");
                cboCell.Items.Add("Quả");
                cboCell.Items.Add("Cái");
                cboCell.Items.Add("Tờ");
                cboCell.Items.Add("Kg");
                cboCell.Items.Add("Con");
                cboCell.Items.Add("Chuyến");
                cboCell.Items.Add("Đ/Cây");
                cboCell.Value = lstCTPhieuXuatHang[i].DonViTinh;
                row.Cells.Add(cboCell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoLuong;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].DonGia;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].ThanhTien;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoKG;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].DonViTinhQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].SoLuongQuyDoi;
                row.Cells.Add(cell);

                cell = new DataGridViewTextBoxCell();
                cell.Value = lstCTPhieuXuatHang[i].Id;
                row.Cells.Add(cell);

                dgvChiTiet.Rows.Add(row);
            }
        }

        private void dgvChiTiet_Enter(object sender, EventArgs e)
        {
            //if (dgvChiTiet.CurrentRow != null)
            //{
            //    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[dgvChiTiet.CurrentRow.Index].Cells[0];
            //}
        }

        private void cboKho_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboKho.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboKho.Text) && cboKho.Text != "")
                {
                    cboKho.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKho.SelectedValue == null)
            {
                cboKho.Text = "";
                cboKho.Focus();
            }
        }

        private void cboKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (KhachHang b in cboKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboKhachHang.Text) && cboKhachHang.Text != "")
                {
                    cboKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhachHang.SelectedValue == null)
            {
                cboKhachHang.Text = "";
                cboKhachHang.Focus();
            }
        }

        private void cboChiNhanhKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhKhachHang b in cboChiNhanhKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboChiNhanhKhachHang.Text) && cboChiNhanhKhachHang.Text != "")
                {
                    cboChiNhanhKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboChiNhanhKhachHang.SelectedValue == null)
            {
                cboChiNhanhKhachHang.Text = "";
            }
        }        

        private void dgvChiTiet_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvChiTiet.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvChiTiet.ClearSelection();
                    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvChiTiet.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                if (dgvChiTiet.CurrentRow.Index != (dgvChiTiet.Rows.Count - 1))
                {
                    if (dgvChiTiet.CurrentRow.Cells[9].Value != null)
                    {
                        int id = Convert.ToInt32(dgvChiTiet.CurrentRow.Cells[9].Value.ToString());
                        List<CTPhieuDoiHang> lstCTPhieuDoiHang = (from ct in GetAllCTPhieuDoiHang()
                                                                    where ct.Id == id
                                                                    select ct).ToList();

                        if (lstCTPhieuDoiHang.Count > 0)
                        {
                            if (!lstDeleteCTPhieuDoiHang.Contains(lstCTPhieuDoiHang[0]))
                                lstDeleteCTPhieuDoiHang.Add(lstCTPhieuDoiHang[0]);
                        }
                    }
                    dgvChiTiet.Rows.RemoveAt(dgvChiTiet.CurrentRow.Index);
                }
            }
        }
        #endregion

        #region Get du lieu

        public List<DonViTinh> GetAllDonViTinh()
        {
            ResultObj resultObj = new ResultObj();
            List<DonViTinh> lstDVT = new List<DonViTinh>();

            resultObj = donvitinhMgt.GetAllDonViTinh();
            lstDVT = (List<DonViTinh>)resultObj.Result;

            return lstDVT;
        }

        public List<KhachHang> GetAllKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khachhangMgt.GetAllKhachHang();
            List<KhachHang> listKhachHang = (List<KhachHang>)resultObj.Result;

            return listKhachHang;
        }

        public List<ChiNhanhKhachHang> GetAllChiNhanhKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhkhachangMgt.GetAllChiNhanhKhachHang();
            List<ChiNhanhKhachHang> listChiNhanhKhachHang = (List<ChiNhanhKhachHang>)resultObj.Result;

            return listChiNhanhKhachHang;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;

            return listChiNhanhCongTy;
        }

        public List<PhieuDoiHang> GetAllPhieuDoiHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = phieudoihangMgt.GetAllPhieuDoiHang();
            List<PhieuDoiHang> listPhieuDoiHang = (List<PhieuDoiHang>)resultObj.Result;

            return listPhieuDoiHang;
        }

        public List<CTPhieuDoiHang> GetAllCTPhieuDoiHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = ctphieudoihangMgt.GetAllCTPhieuDoiHang();
            List<CTPhieuDoiHang> listCTPhieuDoiHang = (List<CTPhieuDoiHang>)resultObj.Result;

            return listCTPhieuDoiHang;
        }

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listHangThanhPham = (List<HangHoa>)resultObj.Result;

            return listHangThanhPham;
        }

        public List<KhayDung> GetAllKhayDung()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khaydungMgt.GetAllKhayDung();
            List<KhayDung> listKhayDung = (List<KhayDung>)resultObj.Result;

            return listKhayDung;
        }

        public List<CTPhieuXuatHang> GetAllCTPhieuXuatHang()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = ctphieuxuathangMgt.GetAllCTPhieuXuatHang();
            List<CTPhieuXuatHang> listCTPhieuXuatHang = (List<CTPhieuXuatHang>)resultObj.Result;

            return listCTPhieuXuatHang;
        }

        public List<Kho> GetAllKho()
        {
            ResultObj resultObj = new ResultObj();
            List<Kho> lstKho = new List<Kho>();

            resultObj = khoMgt.GetAllKho();
            lstKho = (List<Kho>)resultObj.Result;

            return lstKho;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();
            List<QuanLyKho> lstQuanLyKho = new List<QuanLyKho>();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            lstQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return lstQuanLyKho;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }

        #endregion
    }
}
